#include<stdio.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<unistd.h>
#include<assert.h>
#include<stdlib.h>


int main()
{
    pid_t id = fork();
    assert(id != -1);
    
    if(id == 0)
    {
        int cnt = 10;
        while(cnt)
        {
            printf("我是子进程！pid: %d ppid: %d cnt: %d\n",getpid(),getppid(),cnt--);
            sleep(1);
            int *p = NULL;
            *p=8;
        }
        exit(1);
    }
    

    int status = 0;
    while(1)
    {

    
        pid_t ret = waitpid(id,&status,WNOHANG);
    
        if(ret == 0)//子进程没有退出，仅仅检测到子进程没退出
        {
            printf("waidpid.......\n");
        }
        else if(ret == id)
        {
            //函数调用成功，子进程推出成功
            printf("等待成功! ret: %d exit code %d sign %d\n" ,ret,(status>>8)&0xFF,(status&0x7F));
            break;
        }
        else 
        {
           //waitpid调用失败
            printf("waitpid调用失败\n");
            break;
        }
        sleep(1);
    }

//    int status = 0;
//    int ret = waitpid(id,&status,0);
//    if(ret>0)
//    {
//        //printf("等待成功! ret: %d exit code %d sign %d\n" ,ret,(status>>8)&0xFF,(status&0x7F));
//        //printf("等待成功! ret: %d exit code %d sign %d\n" ,ret,(status>>8)&0xFF,(status&0x7F));
//        //判断是否正常退出
//        if(WIFEXITED(status))
//        {
//            printf("exit code: %d\n",WEXITSTATUS(status));//判断子进程运行结果是否ok
//        }
//        else
//        {
//            printf("子进程不正常退出\n");
//        }
//    }


    return 0;
}











